package service

import (
	"context"
	"demo/domain/model"
	"demo/infra/errors"

	"gorm.io/gorm"
)

type UserInfoService struct {
	uRepo   model.UserRepository
	ulrRepo model.UserLoginRecordRepository
	db      *gorm.DB
}

// NewUserInfoService 构造函数
func NewUserInfoService(uRepo model.UserRepository, ulrRepo model.UserLoginRecordRepository, db *gorm.DB) *UserInfoService {
	return &UserInfoService{uRepo: uRepo, ulrRepo: ulrRepo, db: db}
}

// Register 注册用户
func (s *UserInfoService) Register(ctx context.Context, username, password string) error {
	// 检查用户是否已存在
	existing, err := s.uRepo.FindByUserName(ctx, username)
	if err != nil {
		return errors.NewBizError("B0000", "用户名已存在")
	}
	if existing.ID != 0 {
		return errors.NewBizError("B0000", "用户名已存在")
	}
	// 创建用户（领域层处理密码加密）
	user := model.User{
		UserName: username,
		Password: password,
	}
	err1 := s.uRepo.Save(ctx, &user)
	if err1 != nil {
		return err1
	}
	return nil
}

// Login 登录验证
func (s *UserInfoService) Login(ctx context.Context, username, password, loginIp string) (*model.UserSimple, error) {
	user, err := s.uRepo.FindByUserName(ctx, username)
	if err != nil {
		return nil, errors.NewBizError("B0000", "用户名错误")
	}
	if user.Password != password {
		return nil, errors.NewBizError("B0000", "用户密码错误")
	}
	userLoginRecord := &model.UserLoginRecord{
		UserId:  user.ID,
		LoginIp: loginIp,
	}
	s.ulrRepo.Save(ctx, userLoginRecord)
	userSimple := &model.UserSimple{
		ID:       user.ID,
		Username: user.UserName,
	}
	return userSimple, nil
}
